package com.phiture.erp.stock.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.phiture.erp.stock.core.pojo.dto.ErpWarehousePageReqDTO;
import com.phiture.erp.stock.core.pojo.dto.ErpWarehouseSaveReqDTO;
import com.phiture.erp.stock.core.service.ErpWarehouseService;
import com.phiture.erp.stock.dal.entity.ErpWarehouseDO;
import com.phiture.erp.stock.dal.mapper.ErpWarehouseMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static com.phiture.erp.common.constants.ErrorCodeConstants.WAREHOUSE_NOT_ENABLE;
import static com.phiture.erp.common.constants.ErrorCodeConstants.WAREHOUSE_NOT_EXISTS;

/**
 * @author YH
 * @date 2025/4/13
 */

@Service
@RequiredArgsConstructor
public class ErpWarehouseServiceImpl implements ErpWarehouseService {
    private final ErpWarehouseMapper warehouseMapper;

    @Override
    public Long createWarehouse(ErpWarehouseSaveReqDTO createReqDTO) {
        // 插入
        ErpWarehouseDO warehouse = BeanUtils.toBean(createReqDTO, ErpWarehouseDO.class);
        warehouseMapper.insert(warehouse);
        // 返回
        return warehouse.getId();
    }

    @Override
    public void updateWarehouse(ErpWarehouseSaveReqDTO updateReqDTO) {
        // 校验存在
        validateWarehouseExists(updateReqDTO.getId());
        // 更新
        ErpWarehouseDO updateObj = BeanUtils.toBean(updateReqDTO, ErpWarehouseDO.class);
        warehouseMapper.updateById(updateObj);
    }

    @Override
    public void updateWarehouseDefaultStatus(Long id, Boolean defaultStatus) {
        // 1. 校验存在
        validateWarehouseExists(id);

        // 2.1 如果开启，则需要关闭所有其它的默认
        if (defaultStatus) {
            ErpWarehouseDO warehouse = warehouseMapper.selectByDefaultStatus();
            if (warehouse != null) {
                warehouseMapper.updateById(new ErpWarehouseDO().setId(warehouse.getId()).setDefaultStatus(false));
            }
        }
        // 2.2 更新对应的默认状态
        warehouseMapper.updateById(new ErpWarehouseDO().setId(id).setDefaultStatus(defaultStatus));

    }

    @Override
    public void deleteWarehouse(Long id) {
        // 校验存在
        validateWarehouseExists(id);
        // 删除
        warehouseMapper.deleteById(id);
    }

    @Override
    public ErpWarehouseDO getWarehouse(Long id) {
        return warehouseMapper.selectById(id);
    }

    @Override
    public List<ErpWarehouseDO> validWarehouseList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<ErpWarehouseDO> list = warehouseMapper.selectBatchIds(ids);
        Map<Long, ErpWarehouseDO> warehouseMap = convertMap(list, ErpWarehouseDO::getId);
        for (Long id : ids) {
            ErpWarehouseDO warehouse = warehouseMap.get(id);
            if (warehouseMap.get(id) == null) {
                throw exception(WAREHOUSE_NOT_EXISTS);
            }
            if (CommonStatusEnum.isDisable(warehouse.getStatus())) {
                throw exception(WAREHOUSE_NOT_ENABLE, warehouse.getName());
            }
        }
        return list;
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseListByStatus(Integer status) {
        return warehouseMapper.selectListByStatus(status);
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseList(Collection<Long> ids) {
        return warehouseMapper.selectBatchIds(ids);
    }

    @Override
    public Map<Long, ErpWarehouseDO> getWarehouseMap(Collection<Long> ids) {
        return convertMap(getWarehouseList(ids), ErpWarehouseDO::getId);
    }

    @Override
    public PageResult<ErpWarehouseDO> getWarehousePage(ErpWarehousePageReqDTO pageReqDTO) {
        return warehouseMapper.selectPage(pageReqDTO, new LambdaQueryWrapperX<ErpWarehouseDO>()
                .likeIfPresent(ErpWarehouseDO::getName, pageReqDTO.getName())
                .eqIfPresent(ErpWarehouseDO::getStatus, pageReqDTO.getStatus())
                .orderByDesc(ErpWarehouseDO::getId));
    }

    @Override
    public Map<Long, KeyValue<String, Boolean>> getWarehouseMap() {
        List<ErpWarehouseDO> list = warehouseMapper.selectList(ErpWarehouseDO::getDeleted, Boolean.FALSE);
        return CollUtil.isEmpty(list)
                ? Collections.emptyMap()
                : list.stream().collect(Collectors.toMap(ErpWarehouseDO::getId, item -> new KeyValue<>(item.getName(), item.getDefaultStatus())));
    }

    private void validateWarehouseExists(Long id) {
        if (warehouseMapper.selectById(id) == null) {
            throw exception(WAREHOUSE_NOT_EXISTS);
        }
    }
}
